<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="试卷标题"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        创建试卷
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="试卷ID" prop="paperId" sortable="custom" align="center" width="80" />
      <el-table-column label="试卷标题" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.description || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="题目数量" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.questionCount || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总分" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.totalScore || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="考试时长" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.duration || 0 }}分钟</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="statusTagType(row.status)">
            {{ statusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status==='draft'" size="mini" type="success" @click="handleModifyStatus(row,'published')">
            发布
          </el-button>
          <el-button v-if="row.status==='published'" size="mini" type="warning" @click="handleModifyStatus(row,'archived')">
            归档
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 500px; margin-left:50px;">
        <el-form-item label="试卷标题" prop="title">
          <el-input v-model="temp.title" placeholder="请输入试卷标题" />
        </el-form-item>
        <el-form-item label="试卷描述" prop="description">
          <el-input
            v-model="temp.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="请输入试卷描述"
          />
        </el-form-item>
        <el-form-item label="考试时长" prop="duration">
          <el-input-number v-model="temp.duration" :min="1" :max="300" controls-position="right" style="width: 200px" />
          <span style="margin-left: 10px">分钟</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPageData, createPaper, updatePaper, deletePaper, publishPaper, archivePaper } from '@/api/paperApi'
import Pagination from '@/components/Pagination'

export default {
  name: 'PaperCompose',
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined,
        status: undefined,
        sort: '+paperId'
      },
      temp: {
        paperId: undefined,
        title: '',
        description: '',
        duration: 60,
        status: 'draft'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑试卷',
        create: '创建试卷'
      },
      rules: {
        title: [{ required: true, message: '试卷标题是必填项', trigger: 'blur' }],
        duration: [{ required: true, message: '考试时长是必填项', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getPageData(this.listQuery).then(response => {
        this.list = response.data.papers
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'paperId') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+paperId'
      } else {
        this.listQuery.sort = '-paperId'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        paperId: undefined,
        title: '',
        description: '',
        duration: 60,
        status: 'draft'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createPaper(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updatePaper(tempData).then(() => {
            const index = this.list.findIndex(v => v.paperId === this.temp.paperId)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该试卷, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePaper(row.paperId).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      })
    },
    handleModifyStatus(row, status) {
      const action = status === 'published' ? '发布' : '归档'
      this.$confirm(`确定要${action}试卷"${row.title}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const apiCall = status === 'published' ? publishPaper : archivePaper
        apiCall(row.paperId).then(() => {
          row.status = status
          this.$message({
            message: `${action}成功`,
            type: 'success'
          })
        })
      })
    },
    statusTagType(status) {
      const statusMap = {
        draft: '',
        published: 'success',
        archived: 'info'
      }
      return statusMap[status]
    },
    statusText(status) {
      const statusMap = {
        draft: '草稿',
        published: '已发布',
        archived: '已归档'
      }
      return statusMap[status] || status
    }
  }
}
</script>

<style scoped>
.link-type,
.link-type:focus {
  color: #337ab7;
  cursor: pointer;
}

.link-type:hover {
  color: rgb(32, 160, 255);
}
</style>
